#include "StdAfx.h"
#include "clienthandler.h"
#include "debughandler.h"
#include "disco.h"
#include <Process.h>
#include "friendmanager.h"
namespace gloox
{

ClientHandler* ClientHandler::m_clientHandler = NULL;
ClientHandler::ClientHandler(void):m_loginHander(NULL),m_client(NULL),m_presence(Presence::Available, JID())
{
}

ClientHandler::~ClientHandler(void)
{
// 	if (m_client != NULL)
// 		delete m_client;
}

ClientHandler* ClientHandler::clientHandler()
{
	if (m_clientHandler == NULL)
	{
		m_clientHandler = new ClientHandler();
	}

	return m_clientHandler;
}

void ClientHandler::deleteHanlder()
{
	if (m_clientHandler != NULL)
	{
		delete m_clientHandler;
		m_clientHandler = NULL;
	}
}

void ClientHandler::start(const string& username, const string& password, const string& server)
{
	m_username = JID::unescapeNode(username);
	m_password = password;
	m_server = server;

	HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, connectThread, this, 0, NULL);
	CloseHandle(hThread);
}

unsigned int ClientHandler::connectThread(void* pvoid)
{
	ClientHandler* pClientHander = static_cast<ClientHandler*>(pvoid);
	if (pClientHander == NULL) return 1;

	return pClientHander->onClientHandler();
}

unsigned int ClientHandler::onClientHandler()
{
	JID jid( m_username + "@" + m_server + "/gloox" );
	m_client = new Client(jid, m_password);
	m_client->registerConnectionListener(this);
	m_client->registerPresenceHandler(this);
	m_client->disco()->registerDiscoHandler(&g_friendmanager);
	m_client->rosterManager()->registerRosterListener(&g_friendmanager);
	setPresence(Presence::Unavailable);
	//j->registerMessageSessionHandler(this, 0);
	m_client->disco()->setVersion( "messageTest", GLOOX_VERSION, "Linux" );
	m_client->disco()->setIdentity( "client", "bot" );
	m_client->disco()->addFeature( XMLNS_CHAT_STATES );
	StringList ca;
	ca.push_back( "/path/to/cacert.crt" );
	m_client->setCACerts( ca );

	m_client->logInstance().registerLogHandler( LogLevelDebug, LogAreaAll, DebugHandler::logHandler() );


	if( m_client->connect( false ) )
	{
		ConnectionError ce = ConnNoError;
		while( ce == ConnNoError )
		{
			ce = m_client->recv();
		}
		printf( "ce: %d\n", ce );
	}

	return 0;
}


void ClientHandler::onConnect()
{
	if (m_loginHander != NULL)
		m_loginHander->handleLoginResult(ConnNoError);
}

void ClientHandler::onDisconnect(ConnectionError e)
{
	if (m_loginHander != NULL)
		m_loginHander->handleLoginResult(e);
}

bool ClientHandler::onTLSConnect(const CertInfo& info)
{
	return true;
}

void ClientHandler::cleanup()
{

}

void ClientHandler::setPresence(Presence::PresenceType pretype, const string& status)
{
	m_client->setPresence(pretype, 0, status);
}

void ClientHandler::handlePresence(const Presence& presence)
{
	m_presence = presence;
}

}
